package ai;

import com.fasterxml.jackson.databind.ObjectMapper;
import config.aiConfig;
import io.github.briqt.spark4j.SparkClient;
import io.github.briqt.spark4j.constant.SparkApiVersion;
import io.github.briqt.spark4j.model.SparkMessage;
import io.github.briqt.spark4j.model.SparkSyncChatResponse;
import io.github.briqt.spark4j.model.request.SparkRequest;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet("/sparkServlet")
public class SparkManager extends HttpServlet {
    private SparkClient sparkClient;
    private ObjectMapper mapper = new ObjectMapper();

    public void init() {
        sparkClient = new SparkClient();
        sparkClient.appid = aiConfig.getAppid();
        sparkClient.apiKey = aiConfig.getApiKey();
        sparkClient.apiSecret = aiConfig.getApiSecret();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            // 获取用户输入
            String userInput = request.getParameter("message");
            if (userInput == null || userInput.trim().isEmpty()) {
                out.print(mapper.writeValueAsString(Map.of(
                        "status", "error",
                        "message", "输入不能为空"
                )));
                return;
            }

            // 处理用户输入
            List<SparkMessage> messages = new ArrayList<>();
            messages.add(SparkMessage.userContent(userInput));

            SparkRequest sparkRequest = SparkRequest.builder()
                    .messages(messages)
                    .maxTokens(2048)
                    .temperature(0.2)
                    .apiVersion(SparkApiVersion.V3_5)
                    .build();

            SparkSyncChatResponse chatResponse = sparkClient.chatSync(sparkRequest);
            String responseContent = chatResponse.getContent();

            // 返回AI响应
            out.print(mapper.writeValueAsString(Map.of(
                    "status", "success",
                    "message", responseContent
            )));

        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.print(mapper.writeValueAsString(Map.of(
                    "status", "error",
                    "message", e.getMessage()
            )));
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        doPost(request, response);
    }

}